package com.wj.algorithm.lintcode.string;

import java.util.HashMap;
import java.util.Map;

public class P158 {
    
    public boolean anagram(String s, String t) {
        if(s == null || t == null) {
            return false;
        }
        int sl = s.length(), tl = t.length();
        if(sl != tl) {
            return false;
        }
        
        Map<Character, Integer> temp = new HashMap<Character, Integer>();
        for(int i = 0; i < sl; i ++) {
            char ch = s.charAt(i);
            Integer count = temp.get(ch);
            if(count == null) {
                temp.put(ch, 1);
            } else {
                temp.put(ch, count + 1);
            }
        }
        
        for(int i = 0; i < tl; i ++) {
            char ch = t.charAt(i);
            Integer count = temp.get(ch);
            if(count == null) {
                return false;
            } else if(count > 0) {
                temp.put(ch, count - 1);
            } else {
                return false;
            }
        }
        
        for(Integer i : temp.values()) {
            if(i != null && i > 0) {
                return false;
            }
        }
        
        return true;
    }
    
    public static void main(String[] args) {
        P158 p = new P158();
        System.out.println(p.anagram("abcd", "dcab"));
        System.out.println(p.anagram("ab", "ab"));
        System.out.println(p.anagram("ab", "ac"));
    }
}
